package com.mt.mtbletools;

import java.util.ArrayList;
import java.util.List;
import com.mt.help.GlobalVariable;
import com.mt.mtbletools.TalkFragment.Msg.DIR;
import com.mt.mtbletools.R;
import com.mt.sdk.ble.MTBLEDevice;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.base.MTSeriaBase;
import com.mt.sdk.ble.model.BLEBaseAction.ActionStatues;
import com.mt.sdk.ble.model.BLEBaseAction.Option;
import com.mt.sdk.ble.model.ErroCode;
import com.mt.sdk.ble.model.WriteCharactAction;
import com.mt.sdk.ble.model.WriteCharactWithAckAction;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;

public class MTSeriTalkActivity extends FragmentActivity {
	private Handler handl = new Handler();
	private GlobalVariable mGlobalVariable;
	private MTBLEManager manger;
	private MTSeriaBase mBle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_backfragment);

		mGlobalVariable = GlobalVariable.getinstance();
		manger = mGlobalVariable.getBleManger();

		mBle = new MTSeriaBase(getApplicationContext(), manger);
		initFragment();

		getDefaultDatas();

		startConnect();
	}

	// 获取传送过来的数据
	private MTBLEDevice device;
	private int index;

	private void getDefaultDatas() {
		index = getIntent().getIntExtra(ScanFragment.SELECTDEVICE, -1);
		if (index == -1) {
			finish();
			return;
		}
		if (mGlobalVariable.getDeviceList().size() == 0) {
			finish();
			return;
		}
		device = mGlobalVariable.getDeviceList().get(index);
	}

	// 连接
	private ProgressDialog pd;

	private void startConnect() {
		pd = ProgressDialog.show(MTSeriTalkActivity.this, "wait", "正在连接", true, true, new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				mBle.disConnect();
			}
		});

		ErroCode result = mBle.connect(device.getDevice().getAddress(), 1, false, callback);
		if (result.getCode() != 0) { // 连接失败
			return;
		}
	}

	// 初始化fragment
	private TalkFragment talkfragment;
	private int workingmodel = 0;
	private MTSeriFunctionSelectFragment functionselectfragment;
	private FragmentManager fm;

	private void initFragment() {
		fm = getSupportFragmentManager();
		functionselectfragment = new MTSeriFunctionSelectFragment() {

			@Override
			protected void gotoDatasPage() {
				super.gotoDatasPage();
				workingmodel = 0;
				FragmentTransaction ft = fm.beginTransaction();
				ft.replace(R.id.page_continer, talkfragment);
				ft.addToBackStack(null);
				ft.commit();
				
				talkfragment.setProperty(true, false);
				talkfragment.setHisDatas(new ArrayList<TalkFragment.Msg>());
				talkfragment.setConnectStatues(mBle.isConnected());
			}

			@Override
			protected void gotoCmdPage() {
				super.gotoCmdPage();
				workingmodel = 1;
				FragmentTransaction ft = fm.beginTransaction();
				ft.replace(R.id.page_continer, talkfragment);
				ft.addToBackStack(null);
				ft.commit();
				
				talkfragment.setProperty(true, false);
				talkfragment.setHisDatas(new ArrayList<TalkFragment.Msg>());
				talkfragment.setConnectStatues(mBle.isConnected());
			}

		};
		talkfragment = new TalkFragment(getApplicationContext()) {
			@Override
			protected void onSendMsg(Msg msg) {
				super.onSendMsg(msg);

				if (!mBle.isConnected()) {
					System.out.println("!mBle.isConnected()");
					return;
				}

				if (workingmodel == 0) {
					mBle.addWriteDatasAction(new WriteCharactAction(null, msg.getRealmsg(), new Option(1000)){

						@Override
						public void onSuccess() {
							super.onSuccess();
						}

						@Override
						public void onFail(ErroCode erro) {
							super.onFail(erro);
						}
						
					});
				} else {
					mBle.addWriteCmdsAction(new WriteCharactWithAckAction(null, null, msg.getRealmsg(), new Option(1000)){

						// 接收的反馈数据
						@Override
						public void onReciveDatas(BluetoothGattCharacteristic characteristic, byte[] datas) {
							super.onReciveDatas(characteristic, datas);
							setStatues(ActionStatues.DONE);
							String ackcmd = new String(datas);
							Msg msg = new Msg(characteristic, DIR.RECIVE, datas,
									ackcmd);
							talkfragment.receiveSelfdata(msg);
						}

						@Override
						public void onFail(ErroCode erro) {
							super.onFail(erro);
						}
						
					});
				}

			}
		};

		FragmentTransaction ft = fm.beginTransaction();
		ft.replace(R.id.page_continer, functionselectfragment);
		ft.commit();
	}

	// 连接回调
	private MTSeriaBase.CallBack callback = new MTSeriaBase.CallBack() {

		// 连接结果，成功或者失败
		@Override
		public void onConnect(ErroCode errocode) {
			System.out.println("onBaseConnect->" + errocode.toString());
			if ((pd != null) && (pd.isShowing())) {
				pd.dismiss();
			}

			if (errocode.getCode() == 0) {
				return;
			}

			// 连接失败的情况
			Toast.makeText(MTSeriTalkActivity.this, "连接失败->" + errocode.getMsg(), Toast.LENGTH_LONG).show();
		}

		// 尝试重试连接剩余次数
		@Override
		public void reTryConnect(int lasttimes) {
			if ((pd != null) && (pd.isShowing())) {
				pd.setTitle("正在重连->" + lasttimes);
			}
		}

		// 被动断开连接
		@Override
		public void onDisConnect(ErroCode errocode) {
			Toast.makeText(getApplicationContext(), "断开连接", Toast.LENGTH_SHORT).show();
			if(talkfragment != null){
				talkfragment.setConnectStatues(mBle.isConnected());
			}
		}

		// 主动调用断开接口，断开回调
		@Override
		public void onManualDisConnect(ErroCode errocode) {
		}

		// 接收到数据
		@Override
		public void onDatasRecive(BluetoothGattCharacteristic rxd_charact, byte[] datas) {
			if (workingmodel == 0) {
				TalkFragment.Msg msg = new TalkFragment.Msg(rxd_charact, DIR.RECIVE, datas, null);
				talkfragment.receiveSelfdata(msg);
			}
		}

	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mBle.disConnect();
	}
}
